package role

import (
	"sanguo/cluster"
	"sanguo/node/common/transaction"
	"sanguo/node/node_game"
	ss_msg "sanguo/protocol/ss/message"
	ss_rpc "sanguo/protocol/ss/rpc"
	"sanguo/rpc/changeMapChat"
	"sanguo/rpc/enterChat"
	"sanguo/rpc/leaveChat"

	"github.com/golang/protobuf/proto"
)

func (this *Role) EnterChat() {
	if this.NodeChat != nil {
		this.LeaveChat()
	}

	node_chat, err := cluster.Random("chat")
	if nil != err {
		node_game.Debugln("no chat server")
		return
	}

	req := &ss_rpc.EnterChatReq{
		Game:     proto.String(node_game.GetSelfService().ToPeerID().ToString()),
		UserID:   proto.String(this.GetUserID()),
		RoleID:   proto.Uint64(this.GetID()),
		Name:     proto.String(this.GetName()),
		Level:    proto.Int32(this.GetLev()),
		Portrait: proto.Int32(this.data.Portrait),
	}
	enterChat.AsynCall(node_chat, req, transaction.TransTimeoutMs, func(resp *ss_rpc.EnterChatResp, err error) {
		if nil == err && resp.GetOk() == 1 {
			node_game.Debugln(this.user.GetUserID(), "EnterChat ok")
			this.NodeChat = &node_chat
			this.ChatChangeMap()
		} else {
			node_game.Debugln(this.user.GetUserID(), "EnterChat failed:", err, resp.GetOk())
		}
	})
}

func (this *Role) LeaveChat() {
	if this.NodeChat == nil {
		return
	}

	req := &ss_rpc.LeaveChatReq{
		UserID: proto.String(this.GetUserID()),
		RoleID: proto.Uint64(this.GetID()),
	}
	leaveChat.AsynCall(*this.NodeChat, req, transaction.TransTimeoutMs, func(resp *ss_rpc.LeaveChatResp, err error) {
		if nil == err && resp.GetOk() == 1 {
			node_game.Debugln(this.user.GetUserID(), "LeaveChat ok")
			this.NodeChat = nil
		} else {
			node_game.Debugln(this.user.GetUserID(), "LeaveChat failed:", err, resp.GetOk())
		}
	})
}

func (this *Role) ChatChangeMap() {
	if this.NodeChat == nil {
		return
	}
	req := &ss_rpc.ChangeMapChatReq{
		RoleID: proto.Uint64(this.GetID()),
		MapID:  proto.Int32(this.GetMapID()),
	}
	changeMapChat.AsynCall(*this.NodeChat, req, transaction.TransTimeoutMs, func(resp *ss_rpc.ChangeMapChatResp, err error) {
		if nil == err && resp.GetOk() == 1 {
			node_game.Debugln(this.user.GetUserID(), "ChatChangeMap ok")
		} else {
			node_game.Debugln(this.user.GetUserID(), "ChatChangeMap failed:", err, resp.GetOk())
		}
	})
}

func (this *Role) EnterTeamChat(teamID int32) {

}

func (this *Role) LeaveTeamChat() {

}

func (this *Role) OnSystemMsg(content string) {
	if this.NodeChat == nil {
		return
	}
	node_game.Infoln(content)

	arg := &ss_msg.SystemMsg{
		Content: proto.String(content),
	}
	cluster.PostMessage(*this.NodeChat, arg)
}
